//
//  WBNetworkManager+Extension.swift
//  Practise
//
//  Created by flower on 2017/8/24.
//  Copyright © 2017年 lalala. All rights reserved.
//

import Foundation


// MARK: - 封装该项目的网络请求
extension THNetworkManager {
    
    /// 加载新浪微博数据字典数组
    ///
    /// - Parameters:
    ///   - since_id:  若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0。
    ///   - max_id: 若指定此参数，则返回ID小于或等于max_id的微博，默认为0。
    ///   - completion: 完成回调[list: 微博字典数组/是否成功]
    func statusList(since_id: Int64 = 0, max_id: Int64 = 0, completion: @escaping (_ list:[[String: Any]], _ isSuccess: Bool)->()) {
     
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        // Swift 中 Int 可以转换成 AnyObject / 但是 Int64 不行
        let params = ["since_id": "\(since_id)", "max_id": "\(max_id > 0 ? max_id - 1 : 0)"]
        tokenRequest(URLString: urlString, parameters: params) { (
            json, isSuccess) in
            
            //print("JSON数据 \(json ?? "")")
            // 从 json 中 获取 statuses 字典数组
            // 如果 as? 失败, result = nil
            // 提示: 服务器返回的字典就是按照时间的倒序排序的
            guard let result = (json as AnyObject)["statuses"] as? [[String: Any]] else {
                return
            }
            
            completion(result, isSuccess)
        }
        
//        let params = ["access_token": "2.00dPzaQDgnAdrDaa48e67db0VnE5fD"]
//       
//        request(URLString: urlString, parameters: params) { (
//            json, isSuccess) in
//            
//            //print(json ?? "")
//            
//            let result = (json as AnyObject)["statuses"] as? [[String: Any]]
//            completion(result!, isSuccess)
//        }
    }
//    func statusList() {
//
//        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
//        let params = ["access_token": "2.00dPzaQDgnAdrDaa48e67db0VnE5fD"]
//        
//        request(URLString: urlString, parameters: params, completion: (list: [[String: Any]]?, isSuccess: Bool) -> ()) { (
//            json, isSuccess) in
//            
//            // 从 json 中获取 statuses 字典数组
//            // 如果 as? 失败, result = nil
//            let result = (json as AnyObject)["statuses"] as? [[String: Any]]
//            
//            completion(result, isSuccess)
//                }
//    }
    
    // 返回微博的未读数量
    func unreadCount(completion: @escaping (_ count: Int)->()) {
        
        guard let uid = userAccount.uid else {
            return
        }
        
        let urlString = "https://rm.api.weibo.com/2/remind/unread_count.json"
        let params = ["uid": uid]
        
        tokenRequest(URLString: urlString, parameters: params) { (
            json, isSuccess) in
            print(json ?? "")
            
            let dict = json as? [String: Any]
            let count = dict?["status"] as? Int
            completion(count ?? 0)
        }
        
        
    }
}


// MARK: - 用户信息
extension THNetworkManager {
    
    /// 加载当前用户信息 -- 在用户登录之后 立即执行
    func loadUserInfo(completion: @escaping (_ dict: [String: Any])->()) {
        guard let uid = userAccount.uid else {
            return
        }
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        let params = ["uid": uid]
        
        // 发起网络请求
        tokenRequest(URLString: urlString, parameters: params) { (
            json, isSuccess) in
           // print(json)
            
            // 完成回调
            completion(json as? [String: Any] ?? [:])
        }
        
    }
}

// MARK: - OAuth相关方法
extension THNetworkManager {
    
    //提问: 网络请求异步到底应该返回什么?  - 需要什么返回什么
    ///  加装 AccessToken
    ///
    /// - Parameters:
    ///   - code:  授权码
    ///   - completion: 完成回调[是否成功]
    func loadAccessToken(code: String, completion: @escaping (_ isSuccess: Bool)->()) {
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let params = ["client_id":THAppKey,
                      "client_secret":THAppSecret,
                      "grant_type":"authorization_code",
                      "code":code,
                      "redirect_uri":THRedirectURI]
        
        // 发起网络请求
        request(method: .POST, URLString: urlString, parameters: params) { (json, isSuccess) in
           // print(json)
            // 如果请求失败,不会对账户数据产生任何影响
            // 直接用字典设置 userAccount 的属性
            self.userAccount.yy_modelSet(with: (json as? [String: Any]) ?? [:])
            print(self.userAccount)
            
            // 加载当前登录用户信息
            self.loadUserInfo(completion: { (dict) in
                print(dict)
                
                // 使用用户信息字典设置用户账户信息(昵称和头像地址)
                self.userAccount.yy_modelSet(with: dict)
                
                // 保存模型
                self.userAccount.saveAccount()
                
                print(self.userAccount)
                // 用户加载完成后, 完成回调
                completion(isSuccess)
            })
            
            
        }
    }
}
